package cn.edu.tju.elm.init;

import cn.edu.tju.elm.common.constants.RuleType;
import cn.edu.tju.elm.model.entity.RewardRule;
import cn.edu.tju.elm.repository.RewardRuleRepository;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
@RequiredArgsConstructor
public class RewardRuleInitializer {

    private final RewardRuleRepository rewardRuleRepository;

    @PostConstruct
    public void init() {
        initializeDefaultRules();
    }

    private void initializeDefaultRules() {
        log.info("开始检查并初始化默认奖励规则...");

        // 先删除可能存在的重复规则
        List<RewardRule> existingRechargeRules = rewardRuleRepository.findByRuleTypeAndIsActiveTrue(RuleType.RECHARGE);
        Map<BigDecimal, Long> conditionAmountMap = new HashMap<>();
        List<RewardRule> rulesToDelete = new ArrayList<>();

        for (RewardRule rule : existingRechargeRules) {
            BigDecimal conditionAmount = rule.getConditionAmount();
            if (conditionAmountMap.containsKey(conditionAmount)) {
                // 如果已经有相同条件金额的规则，标记这个规则为删除
                rulesToDelete.add(rule);
            } else {
                conditionAmountMap.put(conditionAmount, rule.getId());
            }
        }

        if (!rulesToDelete.isEmpty()) {
            rewardRuleRepository.deleteAll(rulesToDelete);
            log.info("删除了 {} 个重复的充值规则", rulesToDelete.size());
        }

        List<RewardRule> rulesToCreate = new ArrayList<>();

        // 定义我们期望的默认规则
        List<RewardRule> defaultRules = List.of(
                createRechargeRule(new BigDecimal("100.00"), new BigDecimal("5.00"), "RECHARGE_100_5"),
                createRechargeRule(new BigDecimal("500.00"), new BigDecimal("30.00"), "RECHARGE_500_30"),
                createRechargeRule(new BigDecimal("1000.00"), new BigDecimal("100.00"), "RECHARGE_1000_100"),
                createWithdrawRule(new BigDecimal("0.10"), "WITHDRAW_0.10")
        );

        for (RewardRule defaultRule : defaultRules) {
            if (!rewardRuleRepository.existsByRuleKey(defaultRule.getRuleKey())) {
                rulesToCreate.add(defaultRule);
                log.info("需要创建规则: {} - 条件: {}, 奖励: {}, 费率: {}",
                        defaultRule.getRuleType(),
                        defaultRule.getConditionAmount(),
                        defaultRule.getRewardAmount(),
                        defaultRule.getRewardRate());
            } else {
                log.info("规则已存在: {} - 条件: {}, 奖励: {}, 费率: {}",
                        defaultRule.getRuleType(),
                        defaultRule.getConditionAmount(),
                        defaultRule.getRewardAmount(),
                        defaultRule.getRewardRate());
            }
        }

        if (!rulesToCreate.isEmpty()) {
            try {
                rewardRuleRepository.saveAll(rulesToCreate);
                log.info("成功创建 {} 条新的奖励规则", rulesToCreate.size());
            } catch (Exception e) {
                log.error("创建奖励规则失败: {}", e.getMessage(), e);
                // 这里会捕获到数据库唯一约束异常，说明有重复的 ruleKey
                log.error("可能的原因: 存在重复的规则键(rule_key)");
            }
        } else {
            log.info("所有默认奖励规则已存在，无需创建");
        }
    }

    private RewardRule createRechargeRule(BigDecimal conditionAmount, BigDecimal rewardAmount, String ruleKey) {
        LocalDateTime now = LocalDateTime.now();
        return RewardRule.builder()
                .ruleType(RuleType.RECHARGE)
                .conditionAmount(conditionAmount)
                .rewardAmount(rewardAmount)
                .ruleKey(ruleKey)
                .isActive(true)

                .createTime(now)
                .updateTime(now)
                .deleted(false)

                .build();
    }

    private RewardRule createWithdrawRule(BigDecimal rewardRate, String ruleKey) {
        LocalDateTime now = LocalDateTime.now();
        return RewardRule.builder()
                .ruleType(RuleType.WITHDRAW)
                .rewardRate(rewardRate)
                .ruleKey(ruleKey)
                .isActive(true)

                .createTime(now)
                .updateTime(now)
                .deleted(false)

                .build();
    }
}